import {
  Component,
  Input,
  ViewChild,
  ElementRef,
  HostBinding,
} from '@angular/core';

@Component({
  selector: 'fui-avatar',
  templateUrl: './avatar.component.html',
  styleUrls: ['./avatar.component.sass'],
})
export class AvatarComponent {
  @HostBinding('class.fui-avatar') hostClass = true;
  @ViewChild('textEl') textEl: ElementRef;
  textStyles: {
    transform?: string;
    display?: string;
  };
  displayMode: 'img' | 'text' | 'icon' = 'img';

  private _src: string;
  /** Avartar image. */
  @Input()
  set src(value: string) {
    this._src = value;
    this.onChanges();
  }
  get src() {
    return this._src;
  }

  private _icon: string;
  /** Avartar icon if src is not set. */
  @Input()
  set icon(value: string) {
    this._icon = value;
    this.onChanges();
  }
  get icon() {
    return this._icon;
  }

  private _text: string;
  /** Avartar text if src and icon are not set. */
  @Input()
  set text(value: string) {
    this._text = value;
    this.onChanges();
  }
  get text() {
    return this._text;
  }

  /**
   * Avartar size, default to 'md' if not set.
   */
  @Input() set size(size: string) {
    const classList = this.el.nativeElement.classList;
    ['sm', 'md', 'lg'].forEach((_size) => {
      if (classList.contains(`fui-avatar-${_size}`)) {
        classList.remove(`fui-avatar-${_size}`);
      }
    });
    this.el.nativeElement.classList.add(`fui-avatar-${size}`);
    this.onChanges();
  }

  constructor(
    private el: ElementRef,
  ) {
    this.el.nativeElement.classList.add('fui-avatar-md');
  }

  onChanges(): void {
    if (this.src) {
      this.displayMode = 'img';
    } else if (this.icon) {
      this.displayMode = 'icon';
    } else {
      this.displayMode = 'text';
    }

    setTimeout(() => {
      this.calcStringSize();
    });
  }

  calcStringSize() {
    if (this.displayMode !== 'text') {
      return;
    }

    const el = this.textEl && this.textEl.nativeElement;
    if (!el) {
      return;
    }

    const childrenWidth = el.offsetWidth;
    const avatarWidth = this.el.nativeElement.getBoundingClientRect().width;
    const scale = avatarWidth - 8 < childrenWidth ? (avatarWidth - 8) / childrenWidth : 1;
    if (scale === 1) {
      this.textStyles = {};
    } else {
      this.textStyles = {
        transform: `scale(${scale})`,
        display: 'inline-block',
      };
    }
  }

  imgError() {
    if (this.icon) {
      this.displayMode = 'icon';
    } else if (this.text) {
      this.displayMode = 'text';

      setTimeout(() => {
        this.calcStringSize();
      });
    }
  }
}
